package com.sdr.tackvideo.tackvideo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.sdr.tackvideo.tackvideo.SHCallBack.SHCallbackListener;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/5/17.
 */

public class TackVideo implements SHCallbackListener {
    private Activity mActivity;
    private SurfaceView mSurfaceView;

    private SurfaceHolder mHolder;
    private SHCallBack mSHCallBack;

    public TackVideo(Activity activity, SurfaceView surfaceView) {
        mActivity = activity;
        mSurfaceView = surfaceView;
        mHolder = surfaceView.getHolder();
        mSHCallBack = new SHCallBack(this);
        //设置默认路径
        PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + activity.getPackageName();
        TackVideoUtil.checkFilePath(PATH);
    }

    public void init() {
        mHolder.removeCallback(mSHCallBack);
        mHolder.addCallback(mSHCallBack);
    }

    // 默认的路径
    private String PATH;
    //录制的最大时间   默认10秒
    private int maxTime = 10000;
    //录制的最小时间    默认3秒
    private int minTime = 3000;
    // 录制的状态      默认没有录制
    private boolean isRecording = false;

    public TackVideo savePath(String path) {
        PATH = path;
        //TackVideoUtil.checkFilePath(path);
        return this;
    }

    //拍摄照片存储的路径
    private String savePhotoPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
    // 拍摄完照片的文件
    private File photoFile;

    public String getSavePhotoPath() {
        return savePhotoPath;
    }

    public void setSavePhotoPath(String savePhotoPath) {
        this.savePhotoPath = savePhotoPath;
    }

    public File getPhotoFile() {
        return photoFile;
    }

    public void setPhotoFile(File photoFile) {
        this.photoFile = photoFile;
    }

    public String getPATH() {
        return PATH;
    }

    public TackVideo maxTime(int maxTime) {
        this.maxTime = maxTime;
        return this;
    }

    public TackVideo minTime(int minTime) {
        this.minTime = minTime;
        return this;
    }

    public boolean isRecording() {
        return isRecording;
    }

    public void setRecorderListener(RecorderListener listener) {
        mRecorderListener = listener;
    }

    public int getMaxTime() {
        return maxTime;
    }

    public int getMinTime() {
        return minTime;
    }

    private int current = 0;

    public int getCurrent() {
        return current;
    }

    private File mOutputFile;

    public File getOutputFile() {
        return mOutputFile;
    }

    private void setOutputFile(File outputFile) {
        mOutputFile = outputFile;
    }


    private RecorderListener mRecorderListener;
    private Timer mTimer;

    public void startRecord() {
        if (mMediaRecorder == null) {
            mMediaRecorder = new MediaRecorder();
        }
        TackVideoUtil.checkFilePath(getPATH());
        File outputFile = new File(PATH, System.currentTimeMillis() + ".mp4");
        setOutputFile(outputFile);
        TackVideoUtil.checkFile(outputFile);
        if (mMediaRecorder != null) {
            try {
                //开始录制
                mCamera.unlock();
                mMediaRecorder.setCamera(mCamera);
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                mMediaRecorder.setVideoSize(1280, 720);
                // 使用以下代码屏幕可能花屏
//                if (preSize!=null) {
//                    mHolder.setFixedSize(preSize.width,preSize.height);
//                    mMediaRecorder.setVideoSize(preSize.width, preSize.height);
//                }else {
//                    mMediaRecorder.setVideoSize(640, 480);
//                }
                mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
                mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                mMediaRecorder.setVideoEncodingBitRate(1 * 1024 * 1024);
                mMediaRecorder.setVideoFrameRate(24);
                mMediaRecorder.setOutputFile(outputFile.getAbsolutePath());
                mMediaRecorder.setPreviewDisplay(mHolder.getSurface());
                mMediaRecorder.setOrientationHint(90);
                mMediaRecorder.prepare();
                //正式录制
                mMediaRecorder.start();
                isRecording = true;
                current = 0;
                mTimer = new Timer();
                mTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        current += 100;
                        mHandler.sendEmptyMessage(487);
                    }
                }, 20, 100);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 487) {
                mRecorderListener.progress(current);
            }
        }
    };

    //停止拍摄并且保存文件
    public void stopRecordSave(File outputFile) {
        // 如果当前时间小于最小
        if (getCurrent() < getMinTime()) {
            stopRecordNoSave(outputFile);
            mRecorderListener.recordTimeShort();
        } else {
            if (mMediaRecorder != null) {
                mMediaRecorder.stop();
                mMediaRecorder.release();
                isRecording = false;
                mMediaRecorder = null;
                mTimer.cancel();
                mTimer = null;
                mRecorderListener.recordSuccess(outputFile);
            }
        }
    }

    /**
     * 停止视频录制  不存储文件
     *
     * @param file
     */
    private void stopRecordNoSave(File file) {
        if (mMediaRecorder != null && isRecording) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            isRecording = false;
            mMediaRecorder = null;
            mTimer.cancel();
            mTimer = null;
            if (file != null && file.exists()) {
                file.delete();
            }
        }
    }


    /**
     * 拍摄照片
     */

    public void tackPhoto() {
        if (mCamera == null) return;
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                // 将图片保存在 DIRECTORY_DCIM 内存卡中
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                Matrix matrix = new Matrix();
                matrix.setRotate(90);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                File file = new File(getSavePhotoPath(), System.currentTimeMillis() + ".jpg");
                // 创建文件
                if (file.exists()) {
                    file.delete();
                }
                try {
                    file.createNewFile();
                    OutputStream os = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                    os.flush();
                    os.close();
                    mRecorderListener.onPictureTaken(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private Camera mCamera;
    private MediaRecorder mMediaRecorder;

    private Camera.Size preSize;

    public void startPreView(){
        if (mCamera == null) {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        }
        if (mCamera != null) {
            mCamera.setDisplayOrientation(90);
            try {
                mCamera.setPreviewDisplay(mHolder);
                Camera.Parameters parameters = mCamera.getParameters();
                preSize = TackVideoUtil.getCloselyPreSize(true, TackVideoUtil.getScreenWidth(mActivity), TackVideoUtil.getScreenHeight(mActivity), parameters.getSupportedPreviewSizes());
                parameters.setPreviewSize(preSize.width, preSize.height);
                parameters.setPictureSize(preSize.width, preSize.height);
                //实现Camera自动对焦
                List<String> focusModes = parameters.getSupportedFocusModes();
                if (focusModes != null) {
                    for (String mode : focusModes) {
                        mode.contains("continuous-video");
                        parameters.setFocusMode("continuous-video");
                    }
                }
                mCamera.setParameters(parameters);
                mCamera.startPreview();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mHolder = holder;
        startPreView();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            //停止预览并释放摄像头资源
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        if (mMediaRecorder != null) {
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }

    public interface RecorderListener {
        void progress(float currenttime);

        void recordTimeShort();

        void recordSuccess(File file);

        void onPictureTaken(File file);
    }
}
